// 在文件最开始添加调试代码
console.log('student.js 已加载');

// 使用立即执行函数来确保代码执行
(function() {
    console.log('student.js 开始加载');  // 使用 console.log 确保代码执行
    
    // 在全局作用域添加调试函数
    window.debugLog = function(message) {
        console.log(message);  // 使用 console.log 替代 console.log
    };

    // 检查必要的函数是否存在
    if (typeof getToken !== 'function') {
        console.log('错误: getToken 函数未定义');
        return;
    }
    if (typeof getCurrentUser !== 'function') {
        console.log('错误: getCurrentUser 函数未定义');
        return;
    }

    // 在 DOMContentLoaded 之前就检查 token
    const token = getToken();
    const currentUser = getCurrentUser();
    console.log('当前 token: ' + (token ? token.substring(0, 20) + '...' : '未找到'));
    console.log('当前用户: ' + (currentUser ? JSON.stringify(currentUser) : '未找到'));

    // 模拟数据 (为了演示，暂时在此处重新声明，实际应从后端API获取或共享JS文件)
    // 这些数据应该与 admin.js 中的 MOCK 数据保持一致或相关联
    // const MOCK_EXAMS = [
    //     { id: 1, exam_name: '期中数学考试', subject: '数学', exam_time: '2024-05-20T09:00', location: '教学楼A-101', description: '八年级下学期期中考试', create_time: '2024-05-01T10:00:00Z', update_time: '2024-05-02T11:00:00Z' },
    //     { id: 2, exam_name: '期末英语测试', subject: '英语', exam_time: '2024-06-15T14:30', location: '综合楼B-203', description: '八年级下学期期末综合能力测试', create_time: '2024-06-01T08:00:00Z', update_time: '2024-06-01T09:00:00Z' }
    // ]; // MOCK_EXAMS 将不再使用
    const MOCK_CLASSES = [
        { id: 1, class_name: '八年级 (1) 班', head_teacher: '王老师', student_count: 50, create_time: '2023-09-01T09:00:00Z', update_time: '2023-09-01T09:00:00Z' },
        { id: 2, class_name: '八年级 (2) 班', head_teacher: '李老师', student_count: 48, create_time: '2023-09-01T09:05:00Z', update_time: '2023-09-01T09:05:00Z' }
    ];
    const MOCK_STUDENTS = [
        // 注意：currentUser 对象在 auth.js 中模拟，这里MOCK_STUDENTS主要用于查找班级等关联信息
        // 但学生个人信息应该主要来自 currentUser
        { id: 1, stu_no: 'S001', name: '张三', gender: '男', class_id: 1, phone: '13800138001', create_time: '2023-09-05T10:00:00Z', update_time: '2023-09-05T10:00:00Z' },
        { id: 2, stu_no: 'S002', name: '李四', gender: '女', class_id: 1, phone: '13900139002', create_time: '2023-09-05T10:05:00Z', update_time: '2023-09-05T10:05:00Z' },
        { id: 3, stu_no: 'S003', name: '王五', gender: '男', class_id: 2, phone: '13700137003', create_time: '2023-09-05T10:10:00Z', update_time: '2023-09-05T10:10:00Z' }
    ];
    const MOCK_GRADES = [
        { id: 1, student_id: 1, exam_id: 1, score: 85, create_time: '2024-05-21T10:00:00Z', update_time: '2024-05-21T10:00:00Z' },
        { id: 2, student_id: 2, exam_id: 1, score: 92, create_time: '2024-05-21T10:05:00Z', update_time: '2024-05-21T10:05:00Z' },
        { id: 3, student_id: 1, exam_id: 2, score: 78, create_time: '2024-06-16T09:00:00Z', update_time: '2024-06-16T09:00:00Z' }
    ];

    // 辅助函数：格式化日期时间 (与admin.js中类似)
    function formatStudentDateTime(dateTimeStr) {
        if (!dateTimeStr) return 'N/A';
        try {
            const date = new Date(dateTimeStr);
            if (dateTimeStr.includes('T') && dateTimeStr.includes('Z')) {
                 return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
            }
            // For datetime-local like strings, format them if needed or return as is
            if (dateTimeStr.includes('T')) { // Simple check for datetime-local like format
                const [datePart, timePart] = dateTimeStr.split('T');
                return `${datePart} ${timePart}`;
            }
            return dateTimeStr;
        } catch (e) {
            return dateTimeStr;
        }
    }

    // 函数：显示学生页面的 Toast 提示
    function showStudentToast(message, type = 'info', title = '提示') {
        const toastContainer = document.getElementById('toastContainerStudent');
        if (!toastContainer) return;

        let bgColorClass = 'bg-info';
        let iconHtml = '<i class="fas fa-info-circle mr-2"></i>';

        switch (type) {
            case 'success':
                bgColorClass = 'bg-success';
                iconHtml = '<i class="fas fa-check-circle mr-2"></i>';
                title = title === '提示' ? '成功' : title;
                break;
            case 'danger':
            case 'error':
                bgColorClass = 'bg-danger';
                iconHtml = '<i class="fas fa-times-circle mr-2"></i>';
                title = title === '提示' ? '错误' : title;
                break;
            case 'warning':
                bgColorClass = 'bg-warning text-dark';
                iconHtml = '<i class="fas fa-exclamation-triangle mr-2"></i>';
                title = title === '提示' ? '警告' : title;
                break;
        }

        const toastId = 'toast-student-' + Date.now();
        const toastHTML = `
            <div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
                <div class="toast-header ${bgColorClass} text-white">
                    ${iconHtml}
                    <strong class="mr-auto">${title}</strong>
                    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="toast-body">
                    ${message}
                </div>
            </div>
        `;

        toastContainer.insertAdjacentHTML('beforeend', toastHTML);
        const toastElement = document.getElementById(toastId);
        $(toastElement).toast('show');
        $(toastElement).on('hidden.bs.toast', function () {
            $(this).remove();
        });
    }

    // Helper function to show a spinner in a content div (for student page tables)
    function showStudentPageLoadingSpinner(contentDivElement, message = "正在加载数据...") {
        if (contentDivElement) {
            // Preserve title if it exists
            const titleElement = contentDivElement.querySelector('h2');
            contentDivElement.innerHTML = ''; 
            if (titleElement) {
                contentDivElement.appendChild(titleElement.cloneNode(true));
            }
            
            const spinnerHTML = `
                <div class="text-center p-5">
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">加载中...</span>
                    </div>
                    <p class="mt-2">${message}</p>
                </div>
            `;
            contentDivElement.insertAdjacentHTML('beforeend', spinnerHTML);
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOMContentLoaded 事件触发');
        
        // 1. 权限检查
        if (!checkAuth('student')) {
            console.log('权限检查未通过');
            return; 
        }
        console.log('权限检查通过');

        const currentUser = getCurrentUser();
        console.log('当前用户信息:', currentUser);
        
        if (currentUser && currentUser.name) {
            const studentNameSpan = document.getElementById('studentName');
            if (studentNameSpan) {
                studentNameSpan.textContent = currentUser.name;
            }
        }

        const navLinks = document.querySelectorAll('#studentSidebar .nav-link');
        const mainSections = document.querySelectorAll('#mainStudentContent .main-section');

        navLinks.forEach(link => {
            link.addEventListener('click', function(event) {
                event.preventDefault();
                const targetId = this.getAttribute('data-target');

                if (this.id === 'logoutButtonStudent') {
                    logout();
                    return;
                }

                navLinks.forEach(nav => nav.classList.remove('active'));
                this.classList.add('active');

                mainSections.forEach(section => {
                    section.style.display = 'none';
                });

                if (targetId) {
                    const targetSection = document.getElementById(targetId);
                    if (targetSection) {
                        targetSection.style.display = 'block';
                        loadStudentData(targetId, currentUser);
                    }
                }
            });
        });

        const sidebar = document.getElementById('studentSidebar');
        const sidebarCollapseButton = document.getElementById('sidebarCollapseStudent');
        if (sidebar && sidebarCollapseButton) {
            sidebarCollapseButton.addEventListener('click', function() {
                sidebar.classList.toggle('toggled');
            });
        }

        const dashboardLink = document.querySelector('#studentSidebar .nav-link[data-target="student-dashboard-content"]');
        if (dashboardLink) {
            dashboardLink.click(); 
        }

        // 卡片点击跳转功能
        const cardExams = document.getElementById('cardExams');
        if (cardExams) {
            cardExams.addEventListener('click', function() {
                const nav = document.querySelector('#studentSidebar .nav-link[data-target="view-exams-content"]');
                if (nav) nav.click();
            });
        }
        const cardGrades = document.getElementById('cardGrades');
        if (cardGrades) {
            cardGrades.addEventListener('click', function() {
                const nav = document.querySelector('#studentSidebar .nav-link[data-target="view-grades-content"]');
                if (nav) nav.click();
            });
        }

        // 修改密码弹窗逻辑
        const changePasswordBtn = document.getElementById('changePasswordBtn');
        const changePasswordModal = $('#changePasswordModal');
        const changePasswordForm = document.getElementById('changePasswordForm');

        console.log('修改密码按钮元素:', changePasswordBtn);
        console.log('修改密码模态框元素:', changePasswordModal);
        console.log('修改密码表单元素:', changePasswordForm);

        if (changePasswordBtn && changePasswordModal && changePasswordForm) {
            console.log('所有修改密码相关元素都已找到');
            
            changePasswordBtn.addEventListener('click', function() {
                console.log('修改密码按钮被点击');
                // 清空表单
                changePasswordForm.reset();
                changePasswordModal.modal('show');
            });

            changePasswordForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                const oldPassword = document.getElementById('oldPassword').value.trim();
                const newPassword = document.getElementById('newPassword').value.trim();
                const confirmPassword = document.getElementById('confirmPassword').value.trim();
                
                // 添加调试日志
                console.log('开始修改密码流程');
                
                if (!oldPassword || !newPassword || !confirmPassword) {
                    showStudentToast('请填写所有字段', 'warning');
                    return;
                }
                if (newPassword !== confirmPassword) {
                    showStudentToast('两次输入的新密码不一致', 'warning');
                    return;
                }
                if (newPassword.length < 6) {
                    showStudentToast('新密码长度不能少于6位', 'warning');
                    return;
                }
                try {
                    const token = getToken();
                    // 添加调试日志
                    console.log('当前token:', token ? token.substring(0, 20) + '...' : '未找到token');
                    
                    if (!token) {
                        showStudentToast('未找到登录凭证，请重新登录', 'danger');
                        setTimeout(() => {
                            window.location.href = 'login.html';
                        }, 1500);
                        return;
                    }
                    
                    const resp = await fetch('http://localhost:8888/api/students/change-password', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + token
                        },
                        body: JSON.stringify({ oldPassword, newPassword })
                    });
                    
                    // 添加调试日志
                    console.log('修改密码响应状态:', resp.status);
                    const data = await resp.json();
                    console.log('修改密码响应数据:', data);
                    
                    if (resp.status === 401) {
                        removeToken();
                        removeCurrentUser();
                        showStudentToast('登录已过期，请重新登录', 'danger');
                        setTimeout(() => {
                            window.location.href = 'login.html';
                        }, 1500);
                        return;
                    }
                    
                    if (resp.ok && data.code === 1) {
                        showStudentToast('密码修改成功，请重新登录', 'success');
                        changePasswordModal.modal('hide');
                        setTimeout(() => {
                            window.location.href = 'login.html';
                        }, 1500);
                    } else {
                        showStudentToast(data.msg || '密码修改失败', 'danger');
                    }
                } catch (err) {
                    console.error('修改密码请求失败:', err);
                    showStudentToast('请求失败: ' + (err.message || '请稍后再试'), 'danger');
                }
            });
        }
    });

    // 加载仪表盘数据
    async function loadDashboardData() {
        const token = getToken();
        if (!token) {
            showStudentToast('用户未登录或会话已过期，请重新登录。', 'danger');
            return;
        }

        try {
            // 获取学生成绩数据
            const gradesResponse = await fetch('http://localhost:8888/api/student/my-grades', {
                headers: {
                    'Authorization': 'Bearer ' + token
                }
            });

            if (!gradesResponse.ok) {
                throw new Error('获取成绩数据失败');
            }

            const gradesData = await gradesResponse.json();
            if (gradesData.code !== 1) {
                throw new Error(gradesData.msg || '获取成绩数据失败');
            }

            const grades = gradesData.data || [];
            
            // 确保DOM元素已经准备好
            const dashboardContent = document.getElementById('student-dashboard-content');
            if (!dashboardContent) {
                console.error('找不到仪表盘容器元素');
                return;
            }

            // 更新统计数据
            updateDashboardStats(grades);
            
            // 绘制图表
            renderGradeTrendChart(grades);
            renderSubjectGradeChart(grades);

        } catch (error) {
            console.error('加载仪表盘数据失败:', error);
            showStudentToast('加载仪表盘数据失败: ' + error.message, 'danger');
        }
    }

    // 更新仪表盘统计数据
    function updateDashboardStats(grades) {
        console.log('开始更新仪表盘统计数据');
        
        // 更新已参加考试数量
        const totalExamsTakenElement = document.getElementById('totalExamsTakenStat');
        if (totalExamsTakenElement) {
            totalExamsTakenElement.textContent = grades.length;
            console.log('已更新考试数量:', grades.length);
        } else {
            console.warn('未找到考试数量元素');
        }

        // 计算平均成绩
        const averageScoreElement = document.getElementById('averageScoreStat');
        if (averageScoreElement) {
            const averageScore = grades.length > 0 
                ? (grades.reduce((sum, grade) => sum + grade.score, 0) / grades.length).toFixed(1)
                : 0;
            averageScoreElement.textContent = averageScore + '分';
            console.log('已更新平均成绩:', averageScore);
        } else {
            console.warn('未找到平均成绩元素');
        }

        // 更新成绩分布统计
        const gradeDistribution = {
            excellent: 0, // 优秀 (90-100)
            good: 0,      // 良好 (80-89)
            pass: 0,      // 及格 (60-79)
            fail: 0       // 不及格 (0-59)
        };

        grades.forEach(grade => {
            const score = grade.score;
            if (score >= 90) {
                gradeDistribution.excellent++;
            } else if (score >= 80) {
                gradeDistribution.good++;
            } else if (score >= 60) {
                gradeDistribution.pass++;
            } else {
                gradeDistribution.fail++;
            }
        });

        // 更新成绩分布显示
        const excellentCountElement = document.getElementById('excellentCount');
        const goodCountElement = document.getElementById('goodCount');
        const passCountElement = document.getElementById('passCount');
        const failCountElement = document.getElementById('failCount');

        if (excellentCountElement) excellentCountElement.textContent = gradeDistribution.excellent;
        if (goodCountElement) goodCountElement.textContent = gradeDistribution.good;
        if (passCountElement) passCountElement.textContent = gradeDistribution.pass;
        if (failCountElement) failCountElement.textContent = gradeDistribution.fail;

        console.log('已更新成绩分布:', gradeDistribution);
    }

    // 绘制成绩趋势图
    function renderGradeTrendChart(grades) {
        console.log('开始渲染成绩趋势图');
        const chartElement = document.getElementById('gradeTrendChart');
        if (!chartElement) {
            console.warn('未找到成绩趋势图容器');
            return;
        }

        try {
            if (typeof Chart === 'undefined') {
                throw new Error('Chart.js 未加载');
            }

            const ctx = chartElement.getContext('2d');
            
            // 按考试时间排序
            const sortedGrades = [...grades].sort((a, b) => 
                new Date(a.examTime) - new Date(b.examTime)
            );

            const labels = sortedGrades.map(grade => {
                const date = new Date(grade.examTime);
                return `${date.getMonth() + 1}/${date.getDate()}`;
            });

            const scores = sortedGrades.map(grade => grade.score);

            console.log('成绩趋势图数据:', { labels, scores });

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '成绩',
                        data: scores,
                        borderColor: '#4e73df',
                        backgroundColor: 'rgba(78, 115, 223, 0.05)',
                        borderWidth: 2,
                        pointRadius: 3,
                        pointBackgroundColor: '#4e73df',
                        pointBorderColor: '#fff',
                        pointHoverRadius: 5,
                        fill: true
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            ticks: {
                                stepSize: 20
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
            console.log('成绩趋势图渲染完成');
        } catch (error) {
            console.error('渲染成绩趋势图失败:', error);
            showStudentToast('渲染成绩趋势图失败: ' + error.message, 'danger');
        }
    }

    // 绘制科目成绩分布图
    function renderSubjectGradeChart(grades) {
        console.log('开始渲染科目成绩分布图');
        const chartElement = document.getElementById('subjectGradeChart');
        if (!chartElement) {
            console.warn('未找到科目成绩分布图容器');
            return;
        }

        try {
            if (typeof Chart === 'undefined') {
                throw new Error('Chart.js 未加载');
            }

            const ctx = chartElement.getContext('2d');
            
            // 按科目分组计算平均分
            const subjectScores = {};
            grades.forEach(grade => {
                if (!subjectScores[grade.examSubject]) {
                    subjectScores[grade.examSubject] = {
                        total: 0,
                        count: 0
                    };
                }
                subjectScores[grade.examSubject].total += grade.score;
                subjectScores[grade.examSubject].count++;
            });

            const subjects = Object.keys(subjectScores);
            const averages = subjects.map(subject => 
                (subjectScores[subject].total / subjectScores[subject].count).toFixed(1)
            );

            console.log('科目成绩分布图数据:', { subjects, averages });

            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: subjects,
                    datasets: [{
                        label: '平均分',
                        data: averages,
                        backgroundColor: [
                            'rgba(78, 115, 223, 0.8)',
                            'rgba(28, 200, 138, 0.8)',
                            'rgba(246, 194, 62, 0.8)',
                            'rgba(231, 74, 59, 0.8)'
                        ],
                        borderColor: [
                            'rgba(78, 115, 223, 1)',
                            'rgba(28, 200, 138, 1)',
                            'rgba(246, 194, 62, 1)',
                            'rgba(231, 74, 59, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            ticks: {
                                stepSize: 20
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
            console.log('科目成绩分布图渲染完成');
        } catch (error) {
            console.error('渲染科目成绩分布图失败:', error);
            showStudentToast('渲染科目成绩分布图失败: ' + error.message, 'danger');
        }
    }

    // 修改现有的loadStudentData函数，在dashboard部分添加数据加载
    function loadStudentData(targetId, student) {
        const contentDiv = document.getElementById(targetId);
        if (!contentDiv) return;

        const titleElement = contentDiv.querySelector('h2');
        let originalTitleHTML = '';
        if (titleElement) {
            originalTitleHTML = titleElement.outerHTML;
        }

        switch (targetId) {
            case 'student-dashboard-content':
                // 保留仪表盘的HTML结构
                contentDiv.innerHTML = `
                    ${originalTitleHTML}
                    <p>欢迎你, <span id="studentName">${student ? student.name : ''}</span>!</p>

                    <div class="row mt-4">
                        <div class="col-xl-4 col-md-6 mb-4">
                            <div class="card border-left-primary shadow h-100 py-2 card-clickable" id="cardExams">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                                已参加考试</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="totalExamsTakenStat">加载中...</div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-file-alt fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4 col-md-6 mb-4">
                            <div class="card border-left-success shadow h-100 py-2 card-clickable" id="cardGrades">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                                平均成绩</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="averageScoreStat">加载中...</div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-chart-line fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4 col-md-6 mb-4">
                            <div class="card border-left-info shadow h-100 py-2 card-clickable" id="cardDistribution">
                                <div class="card-body">
                                    <div class="row no-gutters align-items-center">
                                        <div class="col mr-2">
                                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                                成绩分布</div>
                                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="gradeDistributionStat">
                                                <div class="small">
                                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                                        <span class="text-success">优秀</span>
                                                        <span id="excellentCount" class="text-success">0</span>
                                                    </div>
                                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                                        <span class="text-info">良好</span>
                                                        <span id="goodCount" class="text-info">0</span>
                                                    </div>
                                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                                        <span class="text-warning">及格</span>
                                                        <span id="passCount" class="text-warning">0</span>
                                                    </div>
                                                    <div class="d-flex justify-content-between align-items-center">
                                                        <span class="text-danger">不及格</span>
                                                        <span id="failCount" class="text-danger">0</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-auto">
                                            <i class="fas fa-chart-pie fa-2x text-gray-300"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row mt-4">
                        <div class="col-xl-6 mb-4">
                            <div class="card shadow card-clickable" id="cardTrend">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">成绩趋势</h6>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container" style="position: relative; height:300px; width:100%">
                                        <canvas id="gradeTrendChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-6 mb-4">
                            <div class="card shadow card-clickable" id="cardSubjectDistribution">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">科目成绩分布</h6>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container" style="position: relative; height:300px; width:100%">
                                        <canvas id="subjectGradeChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                // 渲染后绑定卡片点击事件
                const cardExams = document.getElementById('cardExams');
                if (cardExams) {
                    cardExams.addEventListener('click', function() {
                        const nav = document.querySelector('#studentSidebar .nav-link[data-target="view-exams-content"]');
                        if (nav) nav.click();
                    });
                }
                const cardGrades = document.getElementById('cardGrades');
                if (cardGrades) {
                    cardGrades.addEventListener('click', function() {
                        const nav = document.querySelector('#studentSidebar .nav-link[data-target="view-grades-content"]');
                        if (nav) nav.click();
                    });
                }
                // 新增：成绩分布、成绩趋势、科目成绩分布卡片点击跳转
                const cardDistribution = document.getElementById('cardDistribution');
                if (cardDistribution) {
                    cardDistribution.addEventListener('click', function() {
                        const nav = document.querySelector('#studentSidebar .nav-link[data-target="view-grades-content"]');
                        if (nav) nav.click();
                    });
                }
                const cardTrend = document.getElementById('cardTrend');
                if (cardTrend) {
                    cardTrend.addEventListener('click', function() {
                        const nav = document.querySelector('#studentSidebar .nav-link[data-target="view-grades-content"]');
                        if (nav) nav.click();
                    });
                }
                const cardSubjectDistribution = document.getElementById('cardSubjectDistribution');
                if (cardSubjectDistribution) {
                    cardSubjectDistribution.addEventListener('click', function() {
                        const nav = document.querySelector('#studentSidebar .nav-link[data-target="view-grades-content"]');
                        if (nav) nav.click();
                    });
                }
                // 延迟加载数据，确保DOM已经准备好
                setTimeout(() => {
                    loadDashboardData();
                }, 100);
                break;

            case 'view-exams-content':
                showStudentPageLoadingSpinner(contentDiv, '正在加载考试信息...');
                const token = getToken(); // 从 auth.js 获取token
                if (!token) {
                    showStudentToast('用户未登录或会话已过期，请重新登录。', 'danger');
                    // 可选择重定向到登录页面
                    // window.location.href = 'login.html'; 
                    contentDiv.innerHTML = originalTitleHTML;
                    contentDiv.innerHTML += '<p class="text-danger">请先登录后查看考试信息。</p>';
                    return;
                }

                fetch('http://localhost:8888/api/students/all-exams', { // Corrected URL: /api/students/all-exams (plural)
                    headers: {
                        'Authorization': 'Bearer ' + token // 添加Authorization头
                    }
                })
                    .then(response => {
                        if (response.status === 401) { // 未授权
                            removeToken(); // 清除可能无效的token
                            removeCurrentUser();
                            showStudentToast('会话已过期或无效，请重新登录。', 'danger');
                            // 可选：延迟后重定向到登录页
                            // setTimeout(() => window.location.href = 'login.html', 2000);
                            throw new Error('需要重新登录');
                        }
                        if (!response.ok) {
                            throw new Error('网络响应错误: ' + response.statusText);
                        }
                        return response.json();
                    })
                    .then(responseData => { // Changed variable name for clarity
                        contentDiv.innerHTML = originalTitleHTML; // Re-add title
                        let examsHTML = '<div class="table-responsive"><table class="table table-striped table-bordered"><thead><tr><th>考试名称</th><th>科目</th><th>考试时间</th><th>地点</th><th>描述</th></tr></thead><tbody>';
                        
                        const actualExams = responseData.data; // Access the actual array from the data property

                        if (actualExams && actualExams.length > 0) {
                            actualExams.forEach(exam => {
                                // Backend DTO fields are examName, subject, examTime, location, description
                                examsHTML += `<tr>
                                    <td>${exam.examName || 'N/A'}</td>
                                    <td>${exam.subject || 'N/A'}</td>
                                    <td>${formatStudentDateTime(exam.examTime)}</td>
                                    <td>${exam.location || 'N/A'}</td>
                                    <td>${exam.description || 'N/A'}</td>
                                </tr>`;
                            });
                        } else {
                            examsHTML += '<tr><td colspan="5" class="text-center">暂无考试信息。</td></tr>';
                            // Optionally, provide a toast based on responseData if needed, 
                            // e.g., if code is 1 but data is empty.
                            if (responseData.code === 1 && (!actualExams || actualExams.length === 0)) {
                                showStudentToast('当前没有可显示的考试信息。', 'info');
                            } else if (responseData.code !== 1 && responseData.msg) {
                                showStudentToast(responseData.msg, 'warning');
                            } else if (responseData.code !== 1) {
                                showStudentToast('获取考试信息失败，请稍后再试。', 'danger');
                            }
                        }
                        examsHTML += '</tbody></table></div>';
                        contentDiv.innerHTML += examsHTML;
                    })
                    .catch(error => {
                        console.error('获取考试信息失败:', error);
                        contentDiv.innerHTML = originalTitleHTML; // Re-add title
                        if (error.message === '需要重新登录') {
                             contentDiv.innerHTML += '<p class="text-danger">会话无效，请重新登录后查看考试信息。</p>';
                        } else {
                            contentDiv.innerHTML += '<p class="text-danger">加载考试信息失败，请稍后再试。</p>';
                            showStudentToast('加载考试信息失败: ' + error.message, 'danger');
                        }
                    });
                break;

            case 'view-class-content':
                showStudentPageLoadingSpinner(contentDiv, '正在加载班级信息...');
                const classToken = getToken(); // Re-fetch token for this scope, though it should be same.

                if (!classToken) {
                    showStudentToast('用户未登录或会话已过期，请重新登录。', 'danger');
                    contentDiv.innerHTML = originalTitleHTML;
                    contentDiv.innerHTML += '<p class="text-danger">请先登录后查看班级信息。</p>';
                    return;
                }

                fetch('http://localhost:8888/api/students/my-class-info', {
                    headers: {
                        'Authorization': 'Bearer ' + classToken
                    }
                })
                .then(response => {
                    if (response.status === 401) {
                        removeToken(); removeCurrentUser();
                        showStudentToast('会话已过期或无效，请重新登录。', 'danger');
                        throw new Error('需要重新登录');
                    }
                    if (!response.ok) {
                        // Attempt to parse error from backend if possible
                        return response.json().then(errData => {
                            throw new Error(errData.msg || `网络响应错误: ${response.statusText}`);
                        }).catch(() => {
                            throw new Error(`网络响应错误: ${response.statusText} (无法解析错误详情)`);
                        });
                    }
                    return response.json();
                })
                .then(responseData => {
                    contentDiv.innerHTML = originalTitleHTML; // Re-add title
                    let classHTML = '';
                    if (responseData.code === 1) {
                        const actualClass = responseData.data;
                        if (actualClass) {
                            // Assuming DTO fields: className, headTeacher, studentCount, createTime
                            classHTML = `
                                <h4>我的班级</h4>
                                <ul class="list-group">
                                    <li class="list-group-item"><strong>班级名称:</strong> ${actualClass.className || 'N/A'}</li>
                                    <li class="list-group-item"><strong>班主任:</strong> ${actualClass.headTeacher || 'N/A'}</li>
                                    <li class="list-group-item"><strong>班级人数:</strong> ${actualClass.studentCount === undefined ? 'N/A' : actualClass.studentCount}</li>
                                    <li class="list-group-item"><strong>创建时间:</strong> ${actualClass.createTime ? formatStudentDateTime(actualClass.createTime) : 'N/A'}</li>
                                </ul>`;
                        } else {
                            // This case handles when student is not assigned to a class (data is null but code is 1)
                            classHTML = '<p class="text-info">您尚未分配到任何班级。</p>';
                            showStudentToast('您目前尚未分配到班级。', 'info');
                        }
                    } else {
                        // Error reported by backend (e.g., student not found, class not found for ID)
                        classHTML = `<p class="text-danger">加载班级信息失败: ${responseData.msg || '未知错误'}</p>`;
                        showStudentToast(responseData.msg || '加载班级信息时发生错误。', 'danger');
                    }
                    contentDiv.innerHTML += classHTML;
                })
                .catch(error => {
                    console.error('获取班级信息失败:', error);
                    contentDiv.innerHTML = originalTitleHTML; // Re-add title
                    if (error.message === '需要重新登录') {
                        contentDiv.innerHTML += '<p class="text-danger">会话无效，请重新登录后查看班级信息。</p>';
                    } else {
                        contentDiv.innerHTML += `<p class="text-danger">加载班级信息时出错: ${error.message}</p>`;
                        showStudentToast(`加载班级信息出错: ${error.message}`, 'danger');
                    }
                });
                break;

            case 'view-grades-content':
                showStudentPageLoadingSpinner(contentDiv, '正在加载个人成绩...');
                const gradesToken = getToken();

                if (!gradesToken) {
                    showStudentToast('用户未登录或会话已过期，请重新登录。', 'danger');
                    contentDiv.innerHTML = originalTitleHTML;
                    contentDiv.innerHTML += '<p class="text-danger">请先登录后查看个人成绩。</p>';
                    return;
                }
                
                // fetch(`/api/grades?studentId=${student.studentId}`) // Old URL
                fetch('http://localhost:8888/api/student/my-grades', { // New URL based on SecurityConfig
                    headers: {
                        'Authorization': 'Bearer ' + gradesToken
                    }
                })
                  .then(response => {
                    if (response.status === 401) {
                        removeToken(); removeCurrentUser();
                        showStudentToast('会话已过期或无效，请重新登录。', 'danger');
                        throw new Error('需要重新登录');
                    }
                    if (!response.ok) { 
                        // Try to parse error from backend
                        return response.json().then(errData => {
                            throw new Error(errData.msg || `网络请求失败: ${response.statusText}`);
                        }).catch(() => {
                            throw new Error(`网络请求失败: ${response.statusText} (无法解析错误详情)`);
                        });
                    }
                    return response.json();
                  })
                  .then(responseData => {
                    contentDiv.innerHTML = originalTitleHTML; // Re-add title
                    let gradesHTML = '<div class="table-responsive"><table class="table table-striped table-bordered"><thead><tr><th>考试名称</th><th>科目</th><th>成绩</th><th>考试时间</th><th>录入时间</th></tr></thead><tbody>';
                    
                    const actualGrades = responseData.data; // Assuming grades are in responseData.data

                    if (responseData.code === 1 && actualGrades && actualGrades.length > 0) {
                        actualGrades.forEach(grade => {
                            gradesHTML += `<tr>
                                <td>${grade.examName || 'N/A'}</td>
                                <td>${grade.examSubject || 'N/A'}</td>
                                <td><span class="badge badge-${grade.score >= 60 ? 'success' : 'danger'}">${grade.score === undefined ? 'N/A' : grade.score}</span></td>
                                <td>${formatStudentDateTime(grade.examTime)}</td>
                                <td>${formatStudentDateTime(grade.createTime)}</td>
                            </tr>`;
                        });
                    } else {
                        gradesHTML += '<tr><td colspan="5" class="text-center">您还没有成绩记录。</td></tr>';
                        if (responseData.code === 1) { // Success but no grades
                            showStudentToast('您目前没有成绩记录。', 'info');
                        } else { // Error from backend
                            showStudentToast(responseData.msg || '加载成绩失败，请稍后再试。', 'danger');
                        }
                    }
                    gradesHTML += '</tbody></table></div>';
                    contentDiv.innerHTML += gradesHTML;
                  })
                  .catch(error => {
                    contentDiv.innerHTML = originalTitleHTML;
                    let errorMsgDisplay = `<div class="alert alert-danger mt-3">加载成绩失败：${error.message}</div>`;
                    if (error.message === '需要重新登录') {
                         errorMsgDisplay = '<p class="text-danger">会话无效，请重新登录后查看成绩。</p>';
                    }
                    contentDiv.innerHTML += errorMsgDisplay;
                    showStudentToast('加载成绩失败: ' + error.message, 'danger');
                  });
                break;

            case 'view-profile-content':
                showStudentPageLoadingSpinner(contentDiv, '正在加载个人信息...');
                const profileToken = getToken();

                if (!profileToken) {
                    showStudentToast('用户未登录或会话已过期，请重新登录。', 'danger');
                    contentDiv.innerHTML = originalTitleHTML;
                    contentDiv.innerHTML += '<p class="text-danger">请先登录后查看个人信息。</p>';
                    return;
                }

                fetch('http://localhost:8888/api/student/my-profile', {
                    headers: {
                        'Authorization': 'Bearer ' + profileToken
                    }
                })
                .then(response => {
                    if (response.status === 401) {
                        removeToken(); removeCurrentUser();
                        showStudentToast('会话已过期或无效，请重新登录。', 'danger');
                        throw new Error('需要重新登录');
                    }
                    if (!response.ok) {
                        return response.json().then(errData => {
                            throw new Error(errData.msg || `网络请求失败: ${response.statusText}`);
                        }).catch(() => {
                            throw new Error(`网络请求失败: ${response.statusText} (无法解析错误详情)`);
                        });
                    }
                    return response.json();
                })
                .then(responseData => {
                    contentDiv.innerHTML = originalTitleHTML;
                    let profileHTML = '';
                    if (responseData.code === 1 && responseData.data) {
                        const studentProfile = responseData.data;
                    profileHTML = `
                        <h4>个人信息</h4>
                        <ul class="list-group">
                                <li class="list-group-item"><strong>姓名:</strong> ${studentProfile.name || 'N/A'}</li>
                                <li class="list-group-item"><strong>学号:</strong> ${studentProfile.stuNo || 'N/A'}</li>
                                <li class="list-group-item"><strong>性别:</strong> ${studentProfile.gender || '未设置'}</li>
                                <li class="list-group-item"><strong>班级:</strong> ${studentProfile.className || '未分配'}</li>
                                <li class="list-group-item"><strong>联系电话:</strong> ${studentProfile.phone || '未提供'}</li>
                                <li class="list-group-item"><strong>账号创建时间:</strong> ${formatStudentDateTime(studentProfile.createTime)}</li>
                        </ul>
                        <button class="btn btn-warning mt-3" id="changePasswordBtn">修改密码</button>
                        <!-- 修改密码模态框 -->
                        <div class="modal fade" id="changePasswordModal" tabindex="-1" role="dialog" aria-labelledby="changePasswordModalLabel" aria-hidden="true">
                          <div class="modal-dialog" role="document">
                            <div class="modal-content">
                              <div class="modal-header">
                                <h5 class="modal-title" id="changePasswordModalLabel">修改密码</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  <span aria-hidden="true">&times;</span>
                                </button>
                              </div>
                              <div class="modal-body">
                                <form id="changePasswordForm">
                                  <div class="form-group">
                                    <label for="oldPassword">旧密码</label>
                                    <input type="password" class="form-control" id="oldPassword" required>
                                  </div>
                                  <div class="form-group">
                                    <label for="newPassword">新密码</label>
                                    <input type="password" class="form-control" id="newPassword" required>
                                  </div>
                                  <div class="form-group">
                                    <label for="confirmPassword">确认新密码</label>
                                    <input type="password" class="form-control" id="confirmPassword" required>
                                  </div>
                                  <button type="submit" class="btn btn-primary">提交</button>
                                </form>
                              </div>
                            </div>
                          </div>
                        </div>
                    `;
                } else {
                        profileHTML = '<p class="text-danger">加载个人信息失败: ' + (responseData.msg || '未能获取到学生信息') + '</p>';
                        showStudentToast(responseData.msg || '加载个人信息失败。', 'danger');
                }
                contentDiv.innerHTML += profileHTML;
                // 绑定修改密码弹窗逻辑
                const changePasswordBtn = document.getElementById('changePasswordBtn');
                const changePasswordModal = $('#changePasswordModal');
                const changePasswordForm = document.getElementById('changePasswordForm');
                if (changePasswordBtn && changePasswordModal && changePasswordForm) {
                    changePasswordBtn.addEventListener('click', function() {
                        changePasswordForm.reset();
                        changePasswordModal.modal('show');
                    });
                    changePasswordForm.addEventListener('submit', async function(e) {
                        e.preventDefault();
                        const oldPassword = document.getElementById('oldPassword').value.trim();
                        const newPassword = document.getElementById('newPassword').value.trim();
                        const confirmPassword = document.getElementById('confirmPassword').value.trim();
                        if (!oldPassword || !newPassword || !confirmPassword) {
                            showStudentToast('请填写所有字段', 'warning');
                            return;
                        }
                        if (newPassword !== confirmPassword) {
                            showStudentToast('两次输入的新密码不一致', 'warning');
                            return;
                        }
                        if (newPassword.length < 6) {
                            showStudentToast('新密码长度不能少于6位', 'warning');
                            return;
                        }
                        try {
                            const token = getToken();
                            const resp = await fetch('http://localhost:8888/api/students/change-password', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'Authorization': 'Bearer ' + token
                                },
                                body: JSON.stringify({ oldPassword, newPassword })
                            });
                            const data = await resp.json();
                            if (resp.ok && data.code === 1) {
                                showStudentToast('密码修改成功，请重新登录', 'success');
                                changePasswordModal.modal('hide');
                                setTimeout(() => {
                                    window.location.href = 'login.html';
                                }, 1500);
                            } else {
                                showStudentToast(data.msg || '密码修改失败', 'danger');
                            }
                        } catch (err) {
                            console.error('修改密码请求失败:', err);
                            showStudentToast('请求失败: ' + (err.message || '请稍后再试'), 'danger');
                        }
                    });
                }
                })
                .catch(error => {
                    contentDiv.innerHTML = originalTitleHTML;
                    let errorMsgDisplay = `<div class="alert alert-danger mt-3">加载个人信息失败：${error.message}</div>`;
                    if (error.message === '需要重新登录') {
                        errorMsgDisplay = '<p class="text-danger">会话无效，请重新登录后查看个人信息。</p>';
                    }
                    contentDiv.innerHTML += errorMsgDisplay;
                    showStudentToast('加载个人信息失败: ' + error.message, 'danger');
                });
                break;
        }
    }
})();